package com.ftg.learn.service.impl;

import com.ftg.learn.service.ChatHistoryService;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.data.message.ChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChatHistoryServiceImpl implements ChatHistoryService {

    @Autowired
    private ChatMemoryProvider chatMemoryProvider;
;
    @Override
    public List<String> getReadableChatHistory(String sessionId) {
        try {
            MessageWindowChatMemory memory = (MessageWindowChatMemory) chatMemoryProvider.get(sessionId);
            List<ChatMessage> messages = memory.messages();

            List<String> readableHistory = new ArrayList<>();
            for (ChatMessage message : messages) {
                // 直接使用toString()方法显示消息内容
                if (message.getClass().getSimpleName().equals("UserMessage")) {
                    readableHistory.add("用户: " + message.toString());
                } else if (message.getClass().getSimpleName().equals("AiMessage")) {
                    readableHistory.add("AI: " + message.toString());
                } else if (message.getClass().getSimpleName().equals("SystemMessage")) {
                    readableHistory.add("系统: " + message.toString());
                } else {
                    readableHistory.add("消息: " + message.toString());
                }
            }

            return readableHistory;
        } catch (Exception e) {
            return List.of("获取对话历史失败: " + e.getMessage());
        }
    }
}
